<template>
  <div class="container">
    <header class="header-wrap">
      <h3 class="title">备课教案</h3>
    </header>
    <div class="content-wrap">

      <header class="title">基础信息</header>

      <el-form ref="lessonPlanForm" class="form" :rules="lessonPlanRules" :model="lessonPlanForm" label-width="80px">

        <template v-if="typeRole==='TEACHER'">

        <el-form-item label="学段">

          <el-select v-model="lessonPlanForm.state" placeholder="请选择学段"  @change="changeStage">
            <el-option v-for="item in stateList" :key="'grade'+item.cateId" :label="item.itemName" :value="item.cateId" />
          </el-select>
        </el-form-item>
        <el-form-item  label="科目">

          <el-select  :disabled="baseInfo"  v-model="lessonPlanForm.subject" placeholder="请选择科目" @change="changeSubject">
            <el-option v-for="item in subjectList" :key="'subject'+item.cateId" :label="item.itemName" :value="item.cateId" />
          </el-select>
        </el-form-item>

        <el-form-item label="版本">
          <el-select :disabled="baseInfo" v-model="lessonPlanForm.subjectVersion" placeholder="请选择版本" @change="changeSubjectVersion">
            <el-option v-for="item in subjectVersionList" :key="'subjectVersion'+item.cateId" :label="item.itemName" :value="item.cateId" />
          </el-select>
        </el-form-item>

        <el-form-item label="学期">
          <el-select  :disabled="baseInfo" v-model="lessonPlanForm.grade" placeholder="请选择学期"  @change="changeGrade">
            <el-option v-for="item in gradeList" :key="'state'+item.cateId" :label="item.itemName" :value="item.cateId" />
          </el-select>
        </el-form-item>
        </template>
        <el-form-item label="课题" prop="title">
          <el-autocomplete
            v-model="lessonPlanForm.title"
            :fetch-suggestions="querySearch"
            placeholder="请选择/输入课题，例：小蝌蚪找妈妈"
          />

        </el-form-item>

       <!-- <el-form-item label="总课时">
          <el-input-number v-model="lessonPlanForm.allTimer" @change="handleChange" :min="1" :max="10" label="描述文字"></el-input-number>
        </el-form-item> -->

        <el-button class="nextBtn" type="primary" @click="onNext">下一步</el-button>
      </el-form>
    </div>

  </div>
</template>

<script>
import { findByParentpCateId, findBookChapter } from '@/api/basic'
import { createPersonPrepareLesson, getPersonPrepareLessonDetail,createNotCheckPersonPrepareLesson, updateBaseInfo } from '@/api/personPrepareLesson'
import { mapState, mapMutations } from 'vuex'
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    typeRole: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      //growthClassify:this.$route.params.growthClassify || 10002,//10002;教师成长 //培训 10001 教师成长
      lessonPlanForm: {
        grade: '', // 年级
        state: '', // 学段
        subject: '', // 学科
        subjectVersion: '', // 版本
        title: '',
        typeRole: 'TEACHER',
        allTimer:0
      },
      updateLessonPlanData: {
        growthClassify:this.typeRole === 'TEACHER'?'10001;学科教学':'10002;教师成长',
        grade: '', // 年级
        state: '', // 学段
        subject: '', // 学科
        subjectVersion: '', // 版本
        title: '',
        typeRole: 'TEACHER'
      },
      lessonPlanRules:{
        title:[{required:true,message:'请选择/输入课题，例：小蝌蚪找妈妈'}]
      },
      info:{
        GROWTH_CLASSIFY:'',
        STAGE:'state'
      },
      typeRoleList: [
        {
          label: '培训师',
          value: 'TRAINER'
        },
        {
          label: '老师',
          value: 'TEACHER'
        }
      ],
      gradeList: [],
      subjectList: [],
      subjectVersionList: [],
      stateList: [],
      baseInfo:false,
      titleList: []
    }
  },
  created() {
    this.getGradeData()
  },
  watch:{
    $route:{
      handler(route){
        console.log("route",route)

        //this.updateLessonPlanData.typeRole =  route.prod.typeRole
      },
      immediate: true
    }
  },
  beforeRouteEnter(to,from,next){
    next(vm=>{
    vm.setLoc('hisPage',from.name)
    })
  },
  mounted() {
    if (this.id) {

       this._getPersonPrepareLessonDetail()
    }
  },
  methods: {
    // ...mapMutations({
    //   setFirstTeachingPlan: 'SET_FIRST_TEACHING_PLAN'
    // }),
    async _getPersonPrepareLessonDetail() {
      const params = {
        id: this.id
      }
      let res = await getPersonPrepareLessonDetail(params)
       // res = require('@/api/loc/prepareLessonDetails').details
       console.log("详情",res)
	   if(res.data.baseInfo){

		   this.lessonPlanForm.title = res.data.baseInfo.title
       if(res.data.baseInfo.categoryVOList.length){
       //  this.baseInfo = true
       }
		    this.blankIdVal(res.data.baseInfo.categoryVOList)
	   }
    },
    blankIdVal(categoryVOList){
  // that.updateLessonPlanData['typeRole'] = categoryVOList.filter(list=>list.groupEnum==='GROWTH_CLASSIFY')[0].itemName

  this.lessonPlanForm['state'] = categoryVOList.filter(list=>list.groupEnum==='STAGE')[0]?categoryVOList.filter(list=>list.groupEnum==='STAGE')[0].cateId:''
  this.lessonPlanForm['subject'] = categoryVOList.filter(list=>list.groupEnum==='SUBJECT')[0]?categoryVOList.filter(list=>list.groupEnum==='SUBJECT')[0].cateId:''
  this.lessonPlanForm['grade'] = categoryVOList.filter(list=>list.groupEnum==='GRADE')[0]?categoryVOList.filter(list=>list.groupEnum==='GRADE')[0].cateId:''
  this.lessonPlanForm['subjectVersion'] = categoryVOList.filter(list=>list.groupEnum==='TEXTBOOK_VERSION')[0]?categoryVOList.filter(list=>list.groupEnum==='TEXTBOOK_VERSION')[0].cateId:''
  // this.getGradeData('grade')
  this.getGradeData(this.lessonPlanForm['state'] ,'subject')
  this.getGradeData(this.lessonPlanForm['subject'] ,'subjectVersion')
  this.getGradeData(this.lessonPlanForm['subjectVersion'] ,'grade')
      // this.lessonPlanForm =  that.updateLessonPlanData
    },
    async onNext(e) {
      const params = {

        grade: this.updateLessonPlanData.grade,
        subject: this.updateLessonPlanData.subject,
        growthClassify:this.updateLessonPlanData.growthClassify,
        subjectVersion: this.updateLessonPlanData.subjectVersion,
        state: this.updateLessonPlanData.state,
        title: this.lessonPlanForm.title,
        typeRole: this.typeRole
      }
      if(this.lessonPlanForm.subject.indexOf('语文')>-1)  params.author=this.$store.state.user.name

      this.$refs.lessonPlanForm.validate(async (val) => {
        if(val){
         const res = await createPersonPrepareLesson(params)
      if (this.id||this.$route.query.cp) {
        params.id = this.id
        const res = await updateBaseInfo(params)
        // this.setFirstTeachingPlan(params)
        this.$router.push(`/createResult/uploadLessonPlanDetails/${this.id}`)
      } else {
        if (res.code === '-1') {
          this.$confirm('课题已存在，是否继续新建？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this._createNotCheckPersonPrepareLesson(params)
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
        } else {
          //this.setFirstTeachingPlan(params)
          this.$router.push(`/createResult/uploadLessonPlanDetails/${res.data}`)
        }
      }
      }else{
        console.log('err')
      }
      })
    },
    async _createNotCheckPersonPrepareLesson(params) {
      const res = await createNotCheckPersonPrepareLesson(params)
      this.setFirstTeachingPlan(params)
      this.$router.push(`/createResult/uploadLessonPlanDetails/${res.data}`)
    },
    async getGradeData(pCateId,itemNames) {
      const params = {
        bizTypeEnum: 'PREPARELESSON',
        pCateId:pCateId||'101'
      }
      const res = await findByParentpCateId(params)
     if(!pCateId){
      this.stateList = res.data.categoryVoList
     }else{
      this[itemNames+'List'] = res.data.categoryVoList
     }
    },
    async changeStage(pCateId, e) {
      const params = {
        bizTypeEnum: 'PREPARELESSON',
        pCateId
      }

      this.lessonPlanForm.subject = ''
      this.lessonPlanForm.subjectVersion = ''
      this.lessonPlanForm.grade = ''
      const res = await findByParentpCateId(params)
      this.subjectList = res.data.categoryVoList

      const selectData = this.stateList.find((item) => {
        return item.cateId === pCateId
      })

      this.updateLessonPlanData.state = selectData.itemCode + ';' + selectData.itemName
    },
    async changeSubject(pCateId) {
      const params = {
        bizTypeEnum: 'PREPARELESSON',
        pCateId
      }
      this.lessonPlanForm.grade = ''
      this.lessonPlanForm.subjectVersion = ''
      const res = await findByParentpCateId(params)
      this.subjectVersionList = res.data.categoryVoList

      const selectData = this.subjectList.find((item) => {
        return item.cateId === pCateId
      })
      this.updateLessonPlanData.subject = selectData.itemCode + ';' + selectData.itemName
    },
    async changeSubjectVersion(pCateId) {
      const params = {
        bizTypeEnum: 'PREPARELESSON',
        pCateId
      }
      this.lessonPlanForm.grade = ''
      const res = await findByParentpCateId(params)
      this.gradeList = res.data.categoryVoList
      const selectData = this.subjectVersionList.find((item) => {
        return item.cateId === pCateId
      })
      this.updateLessonPlanData.subjectVersion = selectData.itemCode + ';' + selectData.itemName
    },
    async changeGrade(pCateId) {
      const selectData = this.gradeList.find((item) => {
        return item.cateId === pCateId
      })
      this.updateLessonPlanData.grade = selectData.itemCode + ';' + selectData.itemName

      const params = {
        grade: this.lessonPlanForm.grade,
        state: this.lessonPlanForm.state,
        subject: this.lessonPlanForm.subject,
        vers: this.lessonPlanForm.subjectVersion
      }
      const res = await findBookChapter(params)
      this.titleList = Array.isArray(res.data) ? res.data : []
    },
    handleChange(val){
      console.log('val',val)
    },
    querySearch(queryString, cb) {
      const titleList = this.titleList
      const results = queryString ? titleList.filter(this.createFilter(queryString)) : titleList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 0 42px;
  .header-wrap{
    .title{
      font-size: 20px;
      color: #000;
      line-height: 124px;
      height: 124px;
    }
  }
  .content-wrap{
    box-sizing: border-box;
    border-radius: 16px;
    background: #FFFFFF;
    .title{
      padding: 0 42px;;
      font-size: 16px;
      height: 40px;
      line-height: 40px;
      border-bottom: 1px solid #e2e2e2;
    }
    .form /deep/{
      padding: 40px 0;
      .el-form-item{
        margin-bottom: 40px;
      }
      .el-autocomplete{
        width: 400px;
      }
    }
    .nextBtn{
      margin-left: 40px;
      width: 160px;
    }
  }
}
</style>
